<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, showLoading, hideLoading, showToast, requestPayment } from '@tarojs/taro';
import { getMedicationOrderById, getMedicationOrderDetail, payMedicationOrder } from '@/service/api/nurse_goods';
import { useAuthStore } from '@/store';
import Taro from '@tarojs/taro';


definePageConfig({
  navigationBarTitleText: '订单详情',
});

const order = ref<any>(null);
const orderItems = ref<any[]>([]);
const loading = ref(false);
const router = useRouter();
const authStore = useAuthStore();

onMounted(() => {
  const { id, code } = router.params;
  if (id) {
    fetchOrder(id, code);
  }
});

async function fetchOrder(id: string, code?: string) {
  loading.value = true;
  showLoading({ title: '加载中...' });
  try {
    const [orderRes, itemsRes] = await Promise.all([
      getMedicationOrderById(id),
      getMedicationOrderDetail(code || id),
    ]);

    if (orderRes.success) {
      order.value = orderRes.success;
      if (itemsRes.success) {
        orderItems.value = itemsRes.success.records;
      }
    }
  } catch (error) {
    // Failed to fetch order details
  } finally {
    loading.value = false;
    hideLoading();
  }
}

const getStatusText = (status: string) => {
  if (status === '1') return '未支付';
  if (status === '2') return '已支付';
  return '未知状态';
};

async function handlePay() {
  if (!order.value) return;

  showLoading({ title: '正在支付...' });
  try {
    const res = await payMedicationOrder({
      // id: order.value.id,
      // openid: authStore.openid,
      // outTradeNo: router.params.outTradeNo,
      outTradeNo: order.value.id
    });

    // res


    hideLoading();

    if (res.error) {
        showToast({ title: '支付失败', icon: 'none' });
        return;
    }

    if (res.success) {
      doPay(res.success);
      // requestPayment({
      //   ...success,
      //   success() {
      //     showToast({ title: '支付成功', icon: 'success' });
      //     if (order.value?.id) {
      //         fetchOrder(order.value.id, order.value.code);
      //     }
      //   },
      //   fail(err) {
      //     pay fail
      //     showToast({ title: '支付已取消', icon: 'none' });
      //   },
      // });
    }
  } catch (err) {
    hideLoading();
    showToast({ title: '支付请求失败', icon: 'none' });
    // Payment failed
  }
}



async function doPay(payInfo: any){
    const { timestamp, noncestr, package: packAge, sign } = payInfo;

    Taro.requestPayment({
        timeStamp: timestamp,
        nonceStr: noncestr,
        package: packAge,
        paySign: sign,
        signType: 'RSA',
        fail: () => {
            // if (pay !== '1') gotoOrder();
        },
        complete() {
            // hideLoading();
            // loading.value = false;
        },
        success: res => {
            if (res.errMsg == 'requestPayment:ok') {
                showToast({
                    title: '支付成功！',
                    icon: 'success',
                    duration: 1500
                });
                // setTimeout(() => {
                //     gotoOrder();
                // }, 1500);
            }
        }
    });
}
</script>

<template>
  <basic-layout>
    <view v-if="order" class="order-detail-page">
      <view class="order-card">
        <view class="card-header">
          <h3 class="order-text">{{ order.orderText }}</h3>
          <span class="order-status">{{ getStatusText(order.status) }}</span>
        </view>
        <view class="card-body">
            <view v-for="item in orderItems" :key="item.id" class="product-item">
                <view class="product-name">{{ item.goodsName }}</view>
                <view class="product-info">
                    <view>x{{ item.num }}</view>
                    <view>¥{{ item.price }}</view>
                </view>
            </view>
        </view>
        <view class="card-footer">
          <p>订单时间: {{ order.createTime }}</p>
          <p>订单号: {{ order.code }}</p>
          <p class="total-price">总价: ¥{{ order.totalPrice }}</p>
        </view>
      </view>
      <view v-if="order.status === '1'" class="pay-button-container">
        <nut-button type="primary" block @click="handlePay">立即支付</nut-button>
      </view>
    </view>
    <nut-empty v-else description="订单不存在"></nut-empty>
  </basic-layout>
</template>

<style lang="scss">
.order-detail-page {
  padding: 10px;
}
.order-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
  margin-bottom: 10px;
}
.order-text {
  font-size: 16px;
  font-weight: bold;
}
.order-status {
  font-size: 14px;
  color: #ff6a00;
}
.card-body {
    padding: 10px 0;
}
.product-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
}
.product-name {
    color: #333;
}
.product-info {
    display: flex;
    gap: 20px;
    color: #666;
}
.card-footer {
    border-top: 1px solid #f0f0f0;
    padding-top: 10px;
    font-size: 12px;
    color: #999;
}
.card-footer p {
    line-height: 1.6;
}
.total-price {
    font-weight: bold;
    color: #333;
    font-size: 14px;
    text-align: right;
}

.pay-button-container {
  margin-top: 20px;
  padding: 0 15px;
}
</style> 